package com.ruoyi.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.config.MqttConfig;
import com.ruoyi.entity.Gps;
import com.ruoyi.mavlink.MAVLinkMessage;
import com.ruoyi.mavlink.MAVLinkPacket;
import com.ruoyi.mavlink.Parser;
import com.ruoyi.mavlink.common.msg_gps_raw_int;
import com.ruoyi.service.IGpsService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @Author: 黄龙
 * @Date: 2022/5/7 19:10
 */
@Slf4j
public class OnMessageCallback implements MqttCallback {

    protected MqttConfig mqttConfig = SpringUtils.getBean(MqttConfig.class);
    protected IGpsService iGpsService = SpringUtils.getBean(IGpsService.class);

    private Parser parser = new Parser();

    @Override
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        log.error("<--- MQTT 连接断开，重连中...");
        try {
            mqttConfig.mqttClient();
        } catch (MqttException e) {
            log.error("<--- MQTT 重连失败");
        }
    }
    @Override
    public void messageArrived(String topic, MqttMessage message)  {
        // subscribe后得到的消息会执行到这里面
        //System.out.println("接收消息主题:" + topic);
        //System.out.println("接收消息Qos:" + message.getQos());
       try {
           String s = new String(message.getPayload());
           this.getComType(s);
//           Thread.sleep(1000);
       }catch (Exception e){
           log.error("mqtt, 解析数据错误:{}",e);
       }
    }
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }


    public String getComType(String comType) {
        int length = comType.length();
        for (int i = 0; i < length; i++) {
            if (i * 2 + 2 > comType.length()) {
                //结束
                this.analysis(comType.substring(i * 2, length));
                break;
            }
            this.analysis(comType.substring(i * 2, i * 2 + 2));
        }
        return comType;
    }

    /**
     * 解析
     * @param hex
     */
    public void analysis(String hex){
        if (StringUtils.isEmpty(hex)){return;}
        //解析16进制数据包
        MAVLinkPacket mavLinkPacket = parser.mavlink_parse_char(Integer.decode("0x" + hex));
        if (null != mavLinkPacket){
            //获取对应策略对象
            MAVLinkMessage unpack = mavLinkPacket.unpack();
            //解析数据
            unpack.unpack(mavLinkPacket.payload);
            // System.out.println("数据包类型: " + unpack.name());
            if ("MAVLINK_MSG_ID_GPS_RAW_INT".equals(unpack.name())){
                msg_gps_raw_int gps = (msg_gps_raw_int) unpack;
                //gps
//                System.out.println("飞控gps数据-> int32_t经度: " + gps.lat + " int32_t纬度:" + gps.lon +
//                        " 高度:" +  (gps.alt / 1000) + "米 GPS地面速度" + gps.vel + "cm/s 卫星数量" +
//                        gps.satellites_visible + " 时间戳:" + (DateUtil.date()));
                log.info("飞控gps数据-> int32_t经度: {}, int32_t纬度:{} 高度:{}米 GPS地面速度:{}cm/s 卫星数量:{} 时间:{}",gps.lat,gps.lon,(gps.alt / 1000),gps.vel,gps.satellites_visible,DateUtil.date());
                iGpsService.save(new Gps(gps.lat, gps.lon, gps.alt,gps.vel,gps.satellites_visible,DateUtil.date() ));
            }else if ("MAVLINK_MSG_ID_HEARTBEAT".equals(unpack.name())){
                //过滤后的全球位置（例如融合 GPS 和加速度计）
                //System.out.println(unpack);
            }
        }
    }
}
